<?php
/**
 * 后台Index相关
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;

/**
 * 文章内容管理
 */
class CategoryController extends CommonController {

    public function index() {
        $conds = array();
        $title = $_GET['title'];
        if($title) {
            $conds['title'] = $title;
        }
        if($_GET['id']) {
            $conds['id'] = intval($_GET['id']);
        }

        $page = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
        $pageSize = 10;
        $category = D("Category")->getcat($conds,$page,$pageSize);
        $count = D("Category")->getcatCount($conds);
        $res  =  new \Think\Page($count,$pageSize);
        $pageres = $res->show();

        $this->assign('pageres',$pageres);
        $this->assign('category',$category);
        $this->display();
    }
    public function add(){
        if($_POST) {
            if (!isset($_POST['catname']) || !$_POST['catname']) {
                return show(0, '分类名称为空');
            }
            if ($_POST['id']) {
                return $this->save($_POST);
            }
            $cid = D("Category")->insert($_POST);
            if ($cid) {
                return show(1, '新增成功');
            }
            return show(0, '新增失败');
        }else{
            $this->display();
        }
    }

    public function setStatus() {
        try {
            if ($_POST) {
                $id = $_POST['id'];
                $status = $_POST['status'];
                if (!$id) {
                    return show(0, 'ID不存在');
                }
                $res = D("Category")->updateStatusById($id, $status);
                if ($res) {
                    return show(1, '操作成功');
                } else {
                    return show(0, '操作失败');
                }
            }
            return show(0, '没有提交的内容');
        }catch(Exception $e) {
            return show(0, $e->getMessage());
        }
    }

    public function edit(){
        $id = $_GET['id'];
        $cate = D("Category") -> find($id);
        $this->assign('cate',$cate);
        $this->display();
    }

    public function save($data){
        $id = $data['id'];
        unset($data['id']);
        try {
            $id = D("Category")->updateCateById($id, $data);
            if($id === false) {
                return show(0,'更新失败');
            }
            return show(1,'更新成功');
        }catch(Exception $e) {
            return show(0,$e->getMessage());
        }
    }

}